package com.zlsy.thread.concurrentcontainer;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhouliang
 * @date 2020/8/29 15:08
 * ConcurrentHashMap用在组合操作并不保证线程安全。
 * <p>
 * ConcurrentHashMap保证的是多个线程同时put和get数据是不会错乱的；
 * 但是HashMap是保证不了的；
 */
public class OptionNotSafe implements Runnable {

    private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        scores.put("小明", 0);

        final Thread thread1 = new Thread(new OptionNotSafe());
        final Thread thread2 = new Thread(new OptionNotSafe());

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(scores);

    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
//            final Integer score = scores.get("小明");
//            final int newScore = score + 1;
//            scores.put("小明", newScore);

            /**
             * 保障组合安全的方式 一
             */
            while (true) {
                final Integer score = scores.get("小明");
                final int newScore = score + 1;
                final boolean flag = scores.replace("小明", score, newScore);
                if (flag) {
                    break;
                }
            }
        }
    }
}
